package com.pocketsweet.ui.uilib.adapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.TempMain;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author Kam
 */
public class VoiceAdapter extends BaseListAdapter<MLVoice> {
    private boolean isEdit;
    private boolean isLoading = true;
    List<MLVoice> mlVoice = new ArrayList<MLVoice>();
    private TextView lastVoice = null;// 上次播放的声线

    public AVFile audioFile;
    public String curPlayId = "";// 当前播放的id
    public String playId = "";// 要播放的Id
    public int playItem;// 要播放的Id
    public int curPlayItem;// 当前播放地item
    public MediaPlayer mMediaPlayer;
    public Timer MediaTimer;
    public ArrayList<MLVoice> voiceList = new ArrayList<MLVoice>();

    public VoiceAdapter(Context ctx) {
        super(ctx);
    }

    public VoiceAdapter(Context ctx, List<MLVoice> datas, boolean isEdit) {
        super(ctx, datas);
        this.isEdit = isEdit;
        this.mlVoice = datas;
        if (MLApplication.getInstance().isLogin == true) {
            mMediaPlayer = Main.mMediaPlayer;
            audioFile = Main.audioFile;
            curPlayId = Main.curPlayId;
            playId = Main.playId;
            curPlayItem = Main.curPlayItem;
            MediaTimer = Main.MediaTimer;
        } else {
            mMediaPlayer = TempMain.mMediaPlayer;
            audioFile = TempMain.audioFile;
            curPlayId = TempMain.curPlayId;
            playId = TempMain.playId;
            curPlayItem = TempMain.curPlayItem;
            MediaTimer = TempMain.MediaTimer;
        }


    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            // convertView = inflater.inflate(R.layout.item_voice, parent,
            // false);
            convertView = inflater.inflate(R.layout.item_user_voice, parent,
                    false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // TextView curVoice = (TextView)
        // convertView.findViewById(R.id.tvVoice);
        viewHolder.refreshView(datas.get(position), position);
        // lastVoice = viewHolder.tvVoice;
        return convertView;
    }

    public class ViewHolder implements View.OnClickListener {
        TextView tvVoice;
        TextView btnDelete;
        MLVoice item;
        int position;
        private int playNum = 0;
        private final int TIMERMSG = 0x01;
        private final int OVER = 0x02;
        private final int[] playBg = {R.drawable.img_play_3,
                R.drawable.img_play_2, R.drawable.img_play_1};
        private LoadingDailog loading;
        private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case TIMERMSG:
                        // Log.e("==play", "paly  555");
                        if (playNum >= playBg.length) {
                            break;
                        }
                        Drawable nav_up = ctx.getResources().getDrawable(
                                playBg[playNum]);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
                                nav_up.getMinimumHeight());
                        tvVoice.setCompoundDrawables(null, null, nav_up, null);
                        tvVoice.setBackgroundResource(R.drawable.shape_voice_blue);
                        break;
                    case OVER:
                        // Log.e("==play", "paly  666");
                        mdiaPause();
                        playNum = 0;
                        break;
                }
                super.handleMessage(msg);
            }
        };

        private ViewHolder(View parent) {
            initView(parent);
        }

        public void initView(View parent) {
            btnDelete = (TextView) parent.findViewById(R.id.btnDelete);
            tvVoice = (TextView) parent.findViewById(R.id.tvVoice);
            if (isEdit) {
                btnDelete.setVisibility(View.VISIBLE);
            }
        }

        public void refreshView(MLVoice item, int i) {
            this.item = item;
            this.position = i;
            if (!String.valueOf(item.getTime()).equals("0")) {
                tvVoice.setText(String.valueOf(item.getTime()) + "''");
            }
            // tvVoice.setText(mlUser.getTheme());
            tvVoice.setOnClickListener(this);
            btnDelete.setOnClickListener(this);
            Drawable nav_up = ctx.getResources().getDrawable(
                    R.drawable.img_play_1);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
                    nav_up.getMinimumHeight());
            tvVoice.setCompoundDrawables(null, null, nav_up, null);

        }

        /*
         * 播放音频
         */
        private void play(String audioRemark) {
            if (StringUtils.isEmpty(audioRemark)) {
                ToolKits.toast(ctx, "声线出错啦");
                return;
            }
            // if (playId.equals(curPlayId)) {
            // if (mMediaPlayer.isPlaying()) {
            // mdiaPause();
            // } else {
            // mediaPlay();
            // }
            // } else {
            if (mMediaPlayer == null) {
                ToolKits.toast(ctx, "声线出错啦");
                return;
            }
            if (mMediaPlayer.isPlaying()) {
                mdiaPause();
            }
            playId = curPlayId;
            playItem = curPlayItem;
            mMediaPlayer.reset();
            try {
                isLoading = true; // 正在prepare
                mMediaPlayer.setDataSource(audioRemark);
                mMediaPlayer.prepareAsync(); // 异步准备，不会阻塞ui线程
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ToolKits.toast(ctx, "请稍等");
            mMediaPlayer.setOnPreparedListener(new OnPreparedListener() { // 异步准备成功时执行下一步

                @Override
                public void onPrepared(MediaPlayer arg0) {
                    isLoading = false;
                    mediaPlay();
                }
            });
            // }

        }

        public void mediaPlay() {
            mMediaPlayer.start();
            if (MediaTimer != null) {
                MediaTimer.cancel();
            }
            MediaTimer = new Timer();
            MediaTimer.schedule(new TimerTask() {

                @Override
                public void run() {
                    playNum++;
                    if (playNum > 2) {
                        playNum = 0;
                    }
                    Message message = new Message();
                    message.what = TIMERMSG;
                    handler.sendMessage(message);
                }
            }, 250, 250);
            mMediaPlayer
                    .setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer arg0) {
                            // TODO Auto-generated method stub
                            Message message = new Message();
                            message.what = OVER;
                            handler.sendMessage(message);
                        }
                    });
            mMediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                    // TODO Auto-generated method stub
                    Message message = new Message();
                    message.what = OVER;
                    handler.sendMessage(message);
                    return false;
                }
            });

        }

        public void mediaStop() {
            mMediaPlayer.stop();
            MediaTimer.cancel();
            MediaTimer = new Timer();
            Drawable nav_up = ctx.getResources().getDrawable(
                    R.drawable.img_play_1);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
                    nav_up.getMinimumHeight());
            tvVoice.setCompoundDrawables(null, null, nav_up, null);
            if (lastVoice != null) {
                lastVoice.setCompoundDrawables(null, null, nav_up, null);

            }

        }

        public void mdiaPause() {
            if (mMediaPlayer == null || MediaTimer == null) {
                return;
            }
            mMediaPlayer.pause();
            MediaTimer.cancel();
            Drawable nav_up = ctx.getResources().getDrawable(
                    R.drawable.img_play_1);
            nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
                    nav_up.getMinimumHeight());
            tvVoice.setCompoundDrawables(null, null, nav_up, null);
            if (lastVoice != null) {
                lastVoice.setCompoundDrawables(null, null, nav_up, null);

            }
        }

        @Override
        public void onClick(View v) {
            if (v.equals(tvVoice)) {
                // waiting = ToolKits.createLoadingDialog(ctx, "提交中..");
                // waiting.setText("请稍等");
                // waiting.show();
                if (lastVoice != null) { // 设置上一个声线图片
                    Drawable nav_up = ctx.getResources().getDrawable(
                            R.drawable.img_play_1);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
                            nav_up.getMinimumHeight());
                    lastVoice.setCompoundDrawables(null, null, nav_up, null);
                }
                if (lastVoice != null && lastVoice.equals(v) && isLoading) { // 设置刚创建mediaPlayer取消重复点击，若还没创建好就点击了，则return
                    return;
                }
                curPlayId = item.getObjectId();
                curPlayItem = position;
                play(item.getVoiceUrl());
                lastVoice = (TextView) v;
            }
            if (v.equals(btnDelete)) {
                loading = ToolKits.createLoadingDialog(ctx, "提交中..");
                loading.setText("正在删除");
                loading.show();
                item.deleteInBackground(new DeleteCallback() {

                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            loading.dismiss();
                            voiceList.remove(item);
                            Main.voiceList.remove(item);
                            ToolKits.toast(ctx, "删除成功");
                            if (voiceList.size() <= 0) { // 无声线时
                                UserService.getCurrentUser().setIsHasVoice(
                                        false);
                                UserService.getCurrentUser().saveInBackground();
                            }
                            Intent intent = new Intent();
                            intent.setAction(Main.ACTION_VOICE);
                            ctx.sendBroadcast(intent);
                        } else {
                            loading.dismiss();
                            ToolKits.toast(ctx, "删除失败");

                        }
                    }
                });
                AVQuery<AVObject> query = AVQuery.getQuery("_File");
                query.whereEqualTo("objectId", item.getVoice().getObjectId());
                query.deleteAllInBackground(new DeleteCallback() {

                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            // Log.e("==succeed", "删除成功");
                        } else {
                            // Log.e("==fail", "删除失败" + e.getMessage());

                        }

                    }
                });
            }
        }
    }
}